<template>
  <div class="van-upload-field">
    <div class="img"
         v-for="(item,index) in imgList"
         :key="index"
         @click="$imgDetail(index,imgList)">
      <van-icon name="close"
                class="del"
                @click.stop="imgDel(index)" />
      <img :src="`${imagesUrl}/${item}`"
           alt="" />
    </div>

    <div @click="handlePhoto"
         class="btn">
      <van-icon name="photograph" />
    </div>
    <van-actionsheet v-model="menuFlag"
                     :actions="actions"
                     cancel-text="取消" />
  </div>
</template>

<script>
import { uploadImg, delImg } from '@/api/common';
import { guid } from '@/utils/utils';

export default {
  data () {
    return {
      id: '',
      menuFlag: false,
      photpType: 0,
      actions: [
        {
          name: '拍照',
          callback: this.tophoto,
        },
        {
          name: '图片上传',
          callback: this.toupload,
        },
      ],
      imgList: [],
      imgUrlList: [],
    };
  },
  props: {
    value: '',
    type: '',
    sid: '',
  },
  computed: {
    imgListLen () {
      return this.imgList ? this.imgList.length : 0;
    },
  },
  watch: {
    imgUrlList (n) {
      this.$emit('input', n);
    },
  },
  created () {
    this.setId();
  },
  methods: {
    setId () {
      if (this.$validate.validatenull(this.sid)) {
        this.id = guid();
      } else {
        this.id = this.sid;
      }
      this.$emit('getId', this.id);
    },
    open () {
      this.menuFlag = true;
    },
    upload (imgData) {
      let content = imgData;
      const imgType = content.match(/\/(\S*);/)[1];
      const start = content.indexOf(',') + 1;
      content = content.replace(/[\r\n]/g, "")
      content = content.substring(start);
      uploadImg(this.id, content, this.type, imgType).then((res) => {
        const data = res.data;
        const status = data.status;
        const msg = data.msg;
        if (Number(status) === 500) {
          this.$toast(msg);
          return
        }
        this.imgList.push(data.data.imgPath);
        this.imgUrlList.push(data.data.imgPath);
      });
    },
    // 拍照
    tophoto () {
      this.photpType = 0;
      this.handlePhoto();
    },
    // 图片上传
    toupload () {
      this.photpType = 1;
      this.handlePhoto();
    },
    handlePhoto () {
      window.wx.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          var localIds = res.localIds[0];
          window.wx.getLocalImgData({
            localId: localIds,
            success: (res) => {
              var localData = res.localData;
              if (!localData.includes('base64')) {
                localData = 'data:image/jgp;base64,' + localData
              }
              localData = localData.replace('jgp', 'jpg');
              this.upload(localData);
            },
            fail: (error) => {
              alert(JSON.stringify(error));
            }
          });
        }
      });

    },
    imgDel (index) {
      const item = this.imgUrlList[index];
      this.$dialog
        .confirm({
          title: '提示',
          message: `是否删除序号为${index + 1}的图片`,
        })
        .then(() => delImg(item.id))
        .then(() => {
          this.imgList.splice(index, 1);
          this.imgUrlList.splice(index, 1);
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.van-upload-field {
  padding: 20px 20px;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  .btn,
  .img {
    padding: 2px;
    position: relative;
    margin-right: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 60px;
    height: 60px;
    border: 1px dashed #d0d0d0;
    text-align: center;
    overflow: hidden;
    img {
      width: 100%;
    }
    i {
      font-size: 20px;
      color: #ccc;
    }
  }
  .del {
    position: absolute;
    right: 5px;
    top: 5px;
    font-size: 14px !important;
  }
}
</style>

